package com.example.enews.fragments

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.enews.R
import com.example.enews.activities.NewsDetailActivity
import com.example.enews.adapters.NewsAdapter
import com.example.enews.viewmodels.NewsViewModel
import kotlin.jvm.java

class NewsFragment : Fragment() {

    private lateinit var viewModel: NewsViewModel
    private lateinit var adapter: NewsAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        setupRecyclerView(view)
        return view
    }

    private fun setupRecyclerView(view: View) {
        val recyclerView = view.findViewById<RecyclerView>(R.id.news_recycler)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        // 使用 activity 作用域的 ViewModel，确保数据在 Fragment 重建时保留
        viewModel = ViewModelProvider(requireActivity())[NewsViewModel::class.java]

        if (!::adapter.isInitialized) {
            adapter = NewsAdapter { news ->
                val intent = Intent(requireContext(), NewsDetailActivity::class.java)
                intent.putExtra("news", news)
                startActivity(intent)
            }
            recyclerView.adapter = adapter
        }

        viewModel.newsList.observe(viewLifecycleOwner) {
            adapter.submitList(it)
        }
    }
}



